package cn.stylefeng.guns.modular.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description: easyExcel 导出工具类
 * @Author jzy
 * @Date 2021/9/15 0015
 **/
@Slf4j
public class EasyExcelUtil {

    /**
     * 导出Excel(07版.xlsx)到指定路径下
     * @param path
     * @param excelName
     * @param sheetName
     * @param clazz
     * @param data
     */
    public static void export2File(String path, String excelName, String sheetName, Class clazz, List data) {
        ExcelTypeEnum xlsx = ExcelTypeEnum.XLS;
        String fileName = path.concat(excelName).concat(xlsx.getValue());
        EasyExcel.write(fileName, clazz).excelType(xlsx).sheet(sheetName).doWrite(data);
    }

    /**
     * 导出Excel到web
     * @param response
     * @param excelName
     * @param sheetName
     * @param clazz
     * @param data
     * @throws Exception
     */
    public static void export2Web(HttpServletResponse response, String excelName, String sheetName, Class clazz, List data) throws Exception {
        response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 防止中文文件名乱码
        excelName = URLEncoder.encode(excelName, "UTF-8");
        ExcelTypeEnum xlsx = ExcelTypeEnum.XLSX;
        response.setHeader("Content-disposition", "attachment;filename=" + excelName + xlsx.getValue());
        EasyExcel.write(response.getOutputStream(), clazz).excelType(xlsx).sheet(sheetName).doWrite(data);
    }


}
